import 'package:async/async.dart';
import 'package:boss/models/necessary_order.dart';
import 'package:boss/provider/necessary_order_provider.dart';
import 'package:boss/provider/table_provider.dart';

import 'package:boss/ui/page/necessaryOrder/page/necessaryOrderDetail/provider/necessary_order_detail_provider.dart';
import 'package:boss/ui/page/necessaryOrder/page/necessaryOrderDetail/widget/necessary_order_detail_browser.dart';
import 'package:boss/ui/widget/alert/alert.dart';
import 'package:boss/ui/widget/back_confirmation.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/label_button.dart';
import 'package:boss/ui/widget/loader/loader.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';
import 'package:provider/provider.dart';
import 'package:router/annotation.dart';

@RouterConfig(NecessaryOrderDetailPage.pageName)
class NecessaryOrderDetailPage extends StatefulWidget {
  static const pageName = '/necessaryOrderDetailPage';

  @Autowired()
  final NecessaryOrder data;

  const NecessaryOrderDetailPage({
    Key key,
    this.data,
  }) : super(key: key);

  @override
  _NecessaryOrderDetailPageState createState() => _NecessaryOrderDetailPageState('编辑/新增开台必点项');
}

class _NecessaryOrderDetailPageState extends BaseState<NecessaryOrderDetailPage> {
  _NecessaryOrderDetailPageState(String pageName) : super(pageName);

  bool get isEdit => widget.data != null;

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => NecessaryOrderDetailProvider(data: widget.data),
      child: BackConfirmation(
        backConfirmationText: '开台必点还未完成确认返回么？',
        child: Scaffold(
          appBar: CenterTitleAppBar(
            title: '${isEdit ? '编辑' : '新增'}开台必点项',
            backConfirmationText: '开台必点还未完成确认返回么？',
            actions: <Widget>[
              if (isEdit)
                LabelButton(
                  title: '删除',
                  padding: EdgeInsets.only(left: 8, top: 2, bottom: 2),
                  onTap: () {
                    var necessaryOrderProvider = Provider.of<NecessaryOrderProvider>(
                      context,
                      listen: false,
                    );
                    necessaryOrderProvider.delete(widget.data.necessaryId);
                  },
                )
            ],
          ),
          body: Builder(builder: (context) {
            return Loader(
              loadTask: () => loadTask(context),
              builder: (_) => NecessaryOrderDetailBrowser(),
            );
          }),
        ),
      ),
    );
  }

  Future<Result> loadTask(BuildContext context) async {
    var res = await Provider.of<TableProvider>(context, listen: false).initData();

    if (res.isValue) Provider.of<NecessaryOrderDetailProvider>(context, listen: false).setTables(res.asValue.value);

    return res;
  }
}
